export default {
    name: "addzsmb",
    setup(props, { emit }) {
        const router = VueRouter.useRouter();
        const route = VueRouter.useRoute();
        const formData = ref({name: '',xmid: '',backgroundurl: '',isdefault: false,fields: []});
        const canvasSize = reactive({width: 0,height: 0})
        const xmlist = ref()
        const id = ref();
        const formRef = ref();
        const showFieldDialog = ref(false);
        const bgsx = ref({});
        const fonts = ref([]); //{text: '宋体',value: 'SimSun'}
        
        const rules = reactive({
            name: [
                { required: true, message: '请输入模板名称', trigger: 'blur' },
                { 
                    min: 2, 
                    max: 50, 
                    message: '模板名称长度在 2 到 50 个字符之间', 
                    trigger: 'blur' 
                }
            ],
            xmid: [
                { required: true, message: '请选择项目', trigger: 'change' }
            ],
            backgroundurl: [
                { required: true, message: '请上传背景图', trigger: 'change' }
            ]
        });
        
        onMounted(async() => {
            id.value = route.query.id;
            const storedTemplate = sessionStorage.getItem('currentTemplate');
            const storedXmlist = sessionStorage.getItem('xmlist');
            if(storedTemplate) {
                formData.value = JSON.parse(storedTemplate);
            }
            if(storedXmlist) {
                xmlist.value = JSON.parse(storedXmlist);
            }
            // 处理直接访问的情况
            if(!storedTemplate || !storedXmlist) {
                ElMessage.error('请从正确入口进入');
                router.back();
            }
            await getConfig(); //获取字体配置
            if(formData.value.xmid) {
                bgsx.value = await getbgsxapi({id: Number(formData.value.xmid)}); //获取项目列表
            }
            if(formData.value.backgroundurl) {
                const bgImg = new Image(); //获取背景图大小
                bgImg.src = formData.value.backgroundurl
                await bgImg.decode()
                canvasSize.width = bgImg.width
                canvasSize.height = bgImg.height
            }
        });
        
        watch(() => formData.value.backgroundurl, (newUrl) => {
            if (newUrl) {
                // 确保URL有效性
                const fullUrl = newUrl.startsWith('http') ? newUrl : `${window.APP_CONFIG.baseurl}${newUrl}`;
                // 延迟100ms等待DOM更新
                setTimeout(() => {
                    formData.value.backgroundurl = fullUrl;
                }, 100);
            }
        }, { immediate: true });
        
        const getConfig = async () => {
			const res = await getconfigapi();
            if (res.fonts && typeof res.fonts === 'object') {
                fonts.value = Object.entries(res.fonts).map(([key, value]) => ({
                    text: key,
                    value: value
                }));
            }
		}
        
        // 添加或更新证书模板
        const submit = _.debounce(() => {
            formRef.value.validate(async (valid) => {
                if (valid) {
                    formData.value.id ? await updatepictemp(formData.value) : await addpictemp(formData.value);
                    ElMessage.success('保存成功');
                    sessionStorage.removeItem('currentTemplate');
                    router.push({name: 'AdminZsmb'});
                } else {
                    ElMessage.error('请完善必填项');
                    return false;
                }
            });
        }, 300);
        
        //预览模板
        const showPreview = () => {
            if (!formData.value.backgroundurl || !formData.value.xmid) {
                ElMessage.warning('请先上传背景图并选择项目');
                return;
            }
            const previewData = {
                background: formData.value.backgroundurl,
                fields: formData.value.fields,
                width: canvasSize.width,
                height: canvasSize.height
            };
            let xm = xmlist.value.find(item => String(item.value) === String(formData.value.xmid));
            let xmfields = xm ? xm.fields : null;
            const previewWindow = window.open('', '_blank');
            previewWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <body style="margin:0">
                    <div style="position:relative;width:${previewData.width}px;height:${previewData.height}px">
                        <img src="${previewData.background}" style="position:absolute"/>
                        ${previewData.fields.map(f => {
                            const isImage = xmfields?.[f.name]?.type === 'image';
                            // 关键修改：通过映射表获取字体栈
                            const fontFamily = systemFontMap[f.fontfamily] || systemFontMap.default;
                            const style = [
                                `position:absolute`,
                                `left:${f.x}px`,
                                `top:${f.y}px`,
                                `color:${f.fontcolor || '#000'}`,
                                `font-size:${f.fontsize || 14}px`,
                                `font-family:${fontFamily}`,
                            ];
                            // 图片字段样式
                            if (isImage) {
                                style.push(
                                    `width:${f.width || 100}px`,
                                    `height:${f.height || 100}px`,
                                    `background:rgba(0,0,0,0.1)`,
                                    `border:1px dashed #999`
                                );
                            } else {
                                style.push(
                                    `width:${f.textwidth ? f.textwidth + 'px' : 'auto'}`,
                                    `line-height:${f.rowheight || 24}px`,
                                    `white-space: ${f.textwidth ? 'pre-wrap' : 'nowrap'}`,
                                    `overflow:hidden`
                                );
                            }
                            return `<div style="${style.join(';')}">${xmfields ? xmfields[f.name].name : f.name}</div>`;
                        }).join('')}
                    </div>
                </body>
                </html>
            `);
        };
        
        const handleFieldsUpdate = (updatedFields) => {
            formData.value.fields = updatedFields;
            ElMessage.success('字段配置已更新，请点击保存配置');
        }
        
        const openAdvancedConfig = () => {
            showFieldDialog.value = true;
        };
        
        const beforeImageUpload = (file) => {
            const isImage = file.type.startsWith('image/')
            if (!isImage) {
                ElMessage.error('只能上传图片文件')
                return false
            }
            if (formData.value.backgroundurl) {
                ElMessage.error('只能上传一张图片')
                return false
            }
            return true
        }
        
        //获取项目名
		const getname = (key) => {
			if (!key || !formData.value.xmid || !bgsx.value || !bgsx.value.fields || !bgsx.value.fields[key]) {
				return key;
			}
			return bgsx.value.fields[key].name || '';
		}
		
        // 图片上传处理
        const handleUploadSuccess = (response, field) => {
            if (!response.data) return
            formData.value.backgroundurl = response.data;
        }
        
        // 获取上传类型组件属性
		const getUploadProps = (field) => {
		    var isSingleImage = !!formData.value.backgroundurl; //是否显示上传框
			return {
				action: `${window.APP_CONFIG.baseurl}v1/upload`,
				listType: 'picture-card',
				autoUpload: true,
				accept: '.jpg,.png',
				class: isSingleImage ? ['hide-upload'] : [],
				data: {
				    name: 'file',
                    path: 'zsmb'
                }
			}
		}
		
		 // 文件列表转换器
        const getFileList = () => {
            return computed(() => {
                const value = formData.value.backgroundurl;
                return value ? [{uid: '-1', name: 'backgroundurl', url: value, status: 'success' }] : [];
            }).value;
        }
        
        // 处理文件删除
        const handleRemove = () => {
            formData.value.backgroundurl = '';
        }
        
        // 强制刷新对话框
        const dialogKey = computed(() => {
            return formData.value.xmid + '_' + formData.value.backgroundurl?.slice(-10) // 取URL后10位
        })
        
        return {
            formData,
            xmlist,
            id,
            rules,
            submit,
            showPreview,
            formRef,
            handleFieldsUpdate,
            showFieldDialog,
            openAdvancedConfig,
            beforeImageUpload,
            handleUploadSuccess,
            getname,
            bgsx,
            getUploadProps,
            getFileList,
            handleRemove,
            canvasSize,
            fonts,
            dialogKey
        }
    },
    
    template: `
<div class="app-container">
<div style="margin:20px 0">【证书模板】，要先上传背景图并选择项目后，才能进入字段配置</div>
	<el-card class="form-container">
		<el-form ref="formRef" :model="formData" label-width="120px" label-position="top" :rules="rules">
			<el-form-item label="模板名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入模板名称" />
			</el-form-item>

			<el-form-item label="查询项目" prop="xmid">
				<el-select v-model="formData.xmid" placeholder="选择项目" filterable>
					<el-option v-for="item in xmlist" :key="item.value" :label="item.label"	:value="item.value" />
				</el-select>
			</el-form-item>

			<el-form-item label="背景图片" prop="backgroundurl">
				<el-upload :file-list="getFileList()" v-bind="getUploadProps()" :before-upload="beforeImageUpload" :on-success="handleUploadSuccess" :on-remove="handleRemove">
					<el-icon><Plus /></el-icon>
				</el-upload>
			</el-form-item>

			<el-form-item label="默认模板">
				<el-switch v-model="formData.isdefault" />
			</el-form-item>
		</el-form>

		<div class="field-tip">点击下方字段直接修改坐标，或者点击【高级字段设置】进入完整设置</div>
		<div v-if="formData?.fields" class="field-list">
			<div v-for="(item, index) in formData.fields" :key="item.name" class="field-item">
				<div class="field-name">{{ getname(item.name) }}</div>
				<div class="field-coordinates">
					横X<el-input-number v-model="item.x" :min="0" :step="1" controls-position="right"/>
					纵Y<el-input-number v-model="item.y" :min="0" :step="1" controls-position="right"/>
					字体<el-select v-model="item.fontfamily" style="width:150px">
							<el-option v-for="font in fonts" :key="font.value" :label="font.text" :value="font.value" />
						</el-select>
					字号<el-input-number v-model="item.fontsize" :min="13" :step="1" controls-position="right"/>
					颜色<el-color-picker v-model="item.fontcolor" />
				</div>
			</div>
		</div>

		<div class="action-buttons" v-if="formData.backgroundurl">
			<el-button type="primary" @click="openAdvancedConfig">高级字段配置</el-button>
		</div>
		<div style="margin:20px 0;color:red;">修改后，记得点击保存配置</div>
    	<div class="footer-actions">
    		<el-button type="primary" size="large" @click="submit">保存配置</el-button> &nbsp;&nbsp;
    		<el-button type="info" size="large" @click="showPreview">预览模板</el-button>
    	</div>
	</el-card>


	<zsmbfield v-if="formData?.backgroundurl" :key="dialogKey" v-model="showFieldDialog" :fields="formData.fields" :background-url="formData.backgroundurl" :xmid="formData.xmid" :xmlist="xmlist" :fonts="fonts" @update="handleFieldsUpdate" />
</div>
    
    `
}